//
//  WPAudioRecordVC.m
//  wobingwoyi
//
//  Created by WGP on 2016/11/17.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPAudioRecordVC.h"
#import <AVFoundation/AVFoundation.h>
#import "lame.h"
#import "TZAssetModel.h"

@interface WPAudioRecordVC ()<AVAudioRecorderDelegate>

@property (nonatomic, strong) AVAudioRecorder *audioRecorder;
@property (nonatomic, strong) AVAudioSession *audioSession;
@property(nonatomic,strong)NSTimer *timer;//录音声波监控（注意这里暂时不对播放进行监控）
@property(nonatomic,strong)AVAudioPlayer *audioPlayer;
@property (nonatomic, strong) NSMutableDictionary *settings;

@property(nonatomic,strong)UIButton *cancelBtn;
@property(nonatomic,strong)UIButton *doneBtn;
@property(nonatomic,strong)UIButton *recordBtn;
@property(nonatomic,strong)UILabel *timeLabel;

@property(nonatomic,assign)CGFloat timeLength;
@property(nonatomic,assign)int hours;
@property(nonatomic,assign)int seconds;
@property(nonatomic,assign)int minutes;

@end

@implementation WPAudioRecordVC

static inline NSString* GetAudioDirectoryPathWithAudioName(NSString *audioName) {
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    NSString *directoryPath = [path stringByAppendingPathComponent:@"com.wobingwoyi.audio"];
    NSFileManager *manager = [NSFileManager defaultManager];
    BOOL isCreateSuccess = [manager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
    if (isCreateSuccess) return [directoryPath stringByAppendingPathComponent:audioName];
    return nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RGB_COLOR(31, 33, 36);
    
    [self setupUI];
    
    [self audioSession];
    [self audioRecorder];
}

-(void)setupUI
{
    [self recordBtn];
    [self cancelBtn];
    [self doneBtn];
    [self timeLabel];
}

-(UIButton *)recordBtn
{
    if (_recordBtn == nil)
    {
        _recordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_recordBtn setBackgroundImage:[UIImage imageNamed:@"recordBtn_normal"] forState:UIControlStateNormal];
        [_recordBtn setBackgroundImage:[UIImage imageNamed:@"recordBtn_selected"] forState:UIControlStateSelected];
        [self.view addSubview:_recordBtn];
        [_recordBtn sizeToFit];
        [_recordBtn addTarget:self action:@selector(recordBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        
        CGFloat offset = (SCREEN_HEIGHT/667.0)*538;
        [_recordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.view).offset(offset);
        }];
    }
    return _recordBtn;
}

-(UIButton *)cancelBtn
{
    if (_cancelBtn == nil)
    {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(cancelBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:_cancelBtn];
        
        CGFloat offset = (SCREEN_WIDTH/375.0)*77.5;
        [_cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.recordBtn);
            make.right.equalTo(self.recordBtn.mas_left).offset(-offset);
        }];
    }
    return _cancelBtn;
}

-(UIButton *)doneBtn
{
    if (_doneBtn == nil)
    {
        _doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_doneBtn setTitle:@"完成" forState:UIControlStateNormal];
        [_doneBtn sizeToFit];
        _doneBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        [_doneBtn addTarget:self action:@selector(doneBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:_doneBtn];
        
        CGFloat offset = (SCREEN_WIDTH/375.0)*77.5;
        [_doneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.recordBtn);
            make.left.equalTo(self.recordBtn.mas_right).offset(offset);
        }];
    }
    return _doneBtn;
}

-(NSTimer *)timer
{
    if (_timer == nil)
    {
        _timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    }
    return _timer;
}

-(UILabel *)timeLabel
{
    if (_timeLabel == nil)
    {
        _timeLabel = [UILabel new];
        UIFont *font = [UIFont fontWithName:@"PingFangSC-Light"size:60];//这个是9.0以后自带的平方
        if(font==nil)
        {
        
            font = [UIFont fontWithName:@"STHeitiSC-Light"size:60];
        }
        _timeLabel.font = font;
        _timeLabel.text = @"00:00:00";
        _timeLabel.textColor = [UIColor whiteColor];
        [self.view addSubview:_timeLabel];
        
        CGFloat offset = (SCREEN_HEIGHT/667.0)*135;
        [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.view).offset(offset);
        }];
    }
    return _timeLabel;
}

- (NSString *)originalDataPath
{
    if (!_originalDataPath)
    {
        NSString *dateStr = [[WPDateFormatterManager sharedManager] stringFromDateWithDate:[NSDate date] format:@"yyyy-MM-dd-HH:mm:ss"];
        NSString *originalAudioStr = [NSString stringWithFormat:@"originalAudio-%@.caf",dateStr];
        _originalDataPath = GetAudioDirectoryPathWithAudioName(originalAudioStr);
    }
    return _originalDataPath;
}

- (NSString *)mp3DataPath
{
    if (!_mp3DataPath)
    {
        NSString *dateStr = [[WPDateFormatterManager sharedManager] stringFromDateWithDate:[NSDate date] format:@"yyyy-MM-dd-HH:mm:ss"];
        NSString *mp3NameStr = [NSString stringWithFormat:@"translatedAudio-%@.mp3",dateStr];
        _mp3DataPath = GetAudioDirectoryPathWithAudioName(mp3NameStr);
    }
    return _mp3DataPath;
}

- (AVAudioSession *)audioSession
{
    if (_audioSession == nil)
    {
        _audioSession = [AVAudioSession sharedInstance];
        [_audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        
        if ([_audioSession respondsToSelector:@selector(requestRecordPermission:)])
        {
            [_audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted)
             {
                 if (granted)
                 {
                     NSLog(@"正常录音");
                     [_audioSession setActive:YES error:nil];
                 }
                 else
                 {
                     NSLog(@"失败录音");
                 }
             }];
        }
        [_audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
    }
    return _audioSession;
}

- (NSMutableDictionary *)settings
{
    if (_settings == nil)
    {
        _settings = [NSMutableDictionary dictionary];
//        [_settings setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
        [_settings setObject:@(8000.0f) forKey:AVSampleRateKey];//采样率
        [_settings setObject:@(2) forKey:AVNumberOfChannelsKey]; //双声道
        [_settings setValue:@(16) forKey:AVLinearPCMBitDepthKey];
        [_settings setObject:@(AVAudioQualityHigh) forKey:AVEncoderAudioQualityKey];
    }
    return _settings;
}

-(AVAudioRecorder *)audioRecorder
{
    if (_audioRecorder == nil)
    {
        NSURL *url = [NSURL URLWithString:self.originalDataPath];
        //创建录音格式设置
        NSDictionary *setting=[self settings];
        
        NSError *error = nil;
        _audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate = self;
        if (error)
        {
            NSLog(@"创建录音机对象时发生错误，错误信息：%@",error);
            return nil;
        }
        [_audioRecorder prepareToRecord];
    }
    return _audioRecorder;
}

/**
 *  创建播放器
 *
 *  @return 播放器
 */
-(AVAudioPlayer *)audioPlayer{
    if (!_audioPlayer)
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        //默认情况下扬声器播放
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        [audioSession setActive:YES error:nil];
        
        
        NSError *error=nil;
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:self.mp3DataPath] error:&error];
        _audioPlayer.numberOfLoops=0;
        [_audioPlayer prepareToPlay];
        
        if (error)
        {
            NSLog(@"创建播放器过程中发生错误，错误信息：%@",error);
            return nil;
        }
    }
    return _audioPlayer;
}

#pragma mark - 按钮响应事件方法
-(void)timerAction:(NSTimer *)timer
{
    self.seconds++;
    if (self.seconds == 60)
    {
        self.minutes++;
        self.seconds = 0;
    }
    
    if (self.minutes == 60)
    {
        self.hours++;
        self.minutes = 0;
    }

    self.timeLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d",self.hours,self.minutes,self.seconds];
}

-(void)recordBtnDidClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
    if (btn.selected)
    {
        //录音状态
      [self.audioRecorder record];
        
        if (_timer == nil)
        {
            [self timer];
        }
        else
        {
            [self.timer setFireDate:[NSDate date]];
        }
    }
    else
    {
        //暂停状态
       [self.audioRecorder pause];
       [self.timer setFireDate:[NSDate distantFuture]];
    }
}

-(void)cancelBtnDidClick:(UIButton *)btn
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)doneBtnDidClick:(UIButton *)btn
{
    //停止按钮
    [self.audioRecorder stop];
    self.audioRecorder = nil;
    
    [self.timer invalidate];

}

- (void)mp3TransformWith:(NSString *)originalPath mp3FilePath:(NSString *)mp3FilePath
{
    @try {
        int read, write;
        FILE *pcm = fopen([originalPath cStringUsingEncoding:1], "rb");  //source 被转换的音频文件位置
        if(pcm == NULL)
        {
            NSLog(@"file not found");
        }
        
        fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header,跳过头文件 有的文件录制会有音爆，加上此句话去音爆
        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output 输出生成的Mp3文件位置
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_num_channels(lame, 2);//设置1为单通道，默认为2双通道
        lame_set_in_samplerate(lame, 8000.0);//11025.0
        //lame_set_VBR(lame, vbr_default);
        lame_set_brate(lame, 16);
        lame_set_mode(lame, 3);
        lame_set_quality(lame, 2);
        lame_init_params(lame);
        
        
        
        do {
            read = (int)fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0) {
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            }else{
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            }
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
        //            return YES;
        
        //        return NO;
    }
    @catch (NSException *exception) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"转码失败,是否重新录制?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *again = [UIAlertAction actionWithTitle:@"重新录制" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self audioSession];
            [self audioRecorder];             
        }];
        [alertController addAction:cancel];
        [alertController addAction:again];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
    @finally {
        
        [self dismissViewControllerAnimated:YES completion:nil];
        if ([self.delegate respondsToSelector:@selector(WPAudioRecordVCDoneWith:audio:)]){
            
            TZAssetModel *model = [TZAssetModel new];
            model.type = TZAssetModelMediaTypeAudio;
            
            NSString *urlPath = [NSString stringWithFormat:@"file://%@",self.mp3DataPath];
            model.urlPath = [NSURL URLWithString:urlPath];
            CGFloat totalSecond = self.hours*3600+self.minutes*60+self.seconds;
            model.timeLength = [NSString timeStrWithDurations:totalSecond];
            [self.delegate WPAudioRecordVCDoneWith:self audio:model];
        }
    }
}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    [self mp3TransformWith:self.originalDataPath mp3FilePath:self.mp3DataPath];
}


-(void)dealloc
{
    NSLog(@"录影机死了");
}

@end








